package com.yonyou.pmclouds.im.util;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.pmclouds.im.entity.IMConst;
import com.yonyou.pmclouds.im.entity.IMTokenParamVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
* @Description: IM服务的token信息
*
* @author: zhangwce
* @Date: 2018/4/17
*/
@Slf4j
public class IMTokenInfo {

    // token
    private String token;
    // 超时时间
    private String expiration;

    private static Map<String, String> headers;

    private static volatile IMTokenInfo imTokenInfo;

    private static ObjectMapper mapper = new ObjectMapper();

    private IMTokenInfo(){

    }

    /**
     * 获取IM请求的token
     *
     * @param param
     * @param timeout 是否为超时后的请求
     * @return
     */
    public static IMTokenInfo getImTokenInfo(IMTokenParamVO param, boolean timeout) {
        if (imTokenInfo == null || timeout) {
            synchronized (IMTokenInfo.class) {
                if (imTokenInfo == null || timeout) {
                    imTokenInfo = getImTokenInfoFromServer(param);
                }
            }
        }
        return imTokenInfo;
    }

    /**
     * 重新获取token
     *
     * @param param
     * @return
     */
    private static IMTokenInfo getImTokenInfoFromServer(IMTokenParamVO param){

        String getTokenUrl = IMConst.GET_TOKEN_URL;

        getTokenUrl = getTokenUrl.replace("{etpId}",param.getEtpId());
        getTokenUrl = getTokenUrl.replace("{appId}",param.getAppId());

        String paramJson = getBodyParamJson(param);

        String getTokenResult = IMHttpTookit.doPostWithJson(getTokenUrl,paramJson,getReqHeaders());

        if(StringUtils.isEmpty(getTokenResult))
            return null;
        log.error("IMToken请求结果："+getTokenResult);

        IMTokenInfo tokenInfo = null;
        try {
            tokenInfo = mapper.readValue(getTokenResult,IMTokenInfo.class);
        } catch (Exception e) {
            log.error("转换结果到token出错，具体信息为："+e.getMessage());
        }

        return tokenInfo;

    }
    /**
    * @Description: 构建请求体参数
    * @param: [param]
    * @return: java.lang.String
    * @author: zhangwce
    * @Date: 2018/4/17
    */
    private static String getBodyParamJson(IMTokenParamVO param) {
        Map<String,String> bodyParam = new HashMap<String,String>();
        bodyParam.put("clientId",param.getClientId());
        bodyParam.put("clientSecret",param.getClientSecret());
        String jsonStr = null;
        try {
            jsonStr = mapper.writeValueAsString(bodyParam);
        } catch (JsonProcessingException e) {
            log.error("生成json参数出错，具体信息为："+e.getMessage());
        }
        return jsonStr;
    }
    /**
    * @Description: 获取请求头参数信息
    * @param: []
    * @return: java.util.Map<java.lang.String,java.lang.String>
    * @author: zhangwce
    * @Date: 2018/4/17
    */
    private static Map<String, String> getReqHeaders(){

        if(headers == null || headers.size() == 0){
            headers = new HashMap<String,String>();
            headers.put("Content-Type","application/json");
        }

        return headers;

    }

    public String getToken() {
        return token;
    }

    public String getExpiration() {
        return expiration;
    }
}
